<?php
namespace app\index\controller;
use think\Controller;
use think\Request;
use think\captcha\Captcha;
use think\facade\Session;
use think\facade\Config;
use think\Db;

class Product extends Base
{
	/*产品列表页处理
	列表页存在9种形式的页面
    按照层级关系分类为：
      1 当前分类是否是最小的分类（分类之下没有分类了，这层直接关联产品）
        1.1 是最小分类，但是没有左侧筛选的页面 no_listkey
        1.2 是最小分类，存在左侧分类的页面 min_list

      2 当前分类不是最小分类，存在子类.
        这类页面首先要获取当前分类（含筛选后）的数量
        2.1 当数量小于等于100时，左侧以最小分类id寻找筛选数据，右侧多个表头形式显示 more_title_list
        2.2 当数量大于100时。也存在如下几种情况：
            首先判断是否有左侧列表
            没有:
            2.2.1 不存在tag标记的页面 no_list_and_tag
            2.2.2 存在tag标记的页面 have_tag_no_listkey
            有：

            再次判断是否有筛选数据
            有：
            2.2.3 不存在tag标记的页面 no_tag_have_listket_have_fiter
            2.2.4 存在tag标记的页面  have_tag_have_listket_have_fiter
            没有：
            2.2.5 不存在tag标记的页面 no_tag_have_listkey
            2.2.6 存在tag标记的页面  have_tag_have_listkey
	*/
    public function index(Request $request){
        $class_id = request()->param()['class_id'];
        $get=$request->get();
        if(!empty($get)){
            $get=$this->move_ad_and_replace_p($get);
        }

        $data['base_data']=$this->base_data;

        $get_seo=$get;
        unset($get_seo['page']);
        $class_seo=Db::table('lily_classify_seo')->where([['status','=',1],['class_id','=',$class_id]])->find();
        $data['class_info']=Db::table('lily_classify')->where([['status','=',1],['id','=',$class_id]])->find();/*分类本身数据*/

        $tit_name=$data['class_info']['alias_name'];
        if(empty($get_seo)){
            if(empty($class_seo)){
                $data['seo_title']=$tit_name." | 养贞轴承";
                $data['seo_keywords']=$tit_name;
                $data['seo_desc']="养贞轴承是高质量".$tit_name."的可靠供应商，可在各种应用中提供卓越的性能和耐用性。以优惠的价格购买我们的各种牙科轴承。";
            }else{
                if(empty($class_seo['title'])){
                    $data['seo_title']=$tit_name." | 养贞轴承";
                }else{
                    $data['seo_title']=$class_seo['title'];
                }
                if(empty($class_seo['keywords'])){
                    $data['seo_keywords']=$tit_name;
                }else{
                    $data['seo_keywords']=$class_seo['keywords'];
                }
                if(empty($class_seo['description'])){
                    $data['seo_desc']="养贞轴承是高质量".$tit_name."的可靠供应商，可在各种应用中提供卓越的性能和耐用性。以优惠的价格购买我们的各种牙科轴承。";
                }else{
                    $data['seo_desc']=$class_seo['description'];
                }
            }
        }else{
            $SEOstr='';
            foreach ($get_seo as $key => $value) {
                $SEOstr.=lang(str_replace('_',' ',$key)).':'.lang($value).',';
            }
            $SEOstr=rtrim($SEOstr,',');
            if(empty($class_seo)){
                $data['seo_title']=$SEOstr." ".$tit_name." | 养贞轴承";
                $data['seo_keywords']=$SEOstr." ".$tit_name;
                $data['seo_desc']="LILY轴承是高质量".$SEOstr.$tit_name."的可靠供应商，可在广泛的应用中提供卓越的性能和耐用性。以优惠的价格购买我们的各种牙科轴承。";
            }else{
                if(empty($class_seo['filter_title'])){
                    $data['seo_title']=$SEOstr." ".$tit_name." | 养贞轴承";
                }else{
                    $data['seo_title']=str_replace('[SEOstr]',$SEOstr,$class_seo['filter_title']);
                }

                if(empty($class_seo['filter_keywords'])){
                    $data['seo_keywords']=$SEOstr." ".$tit_name;
                }else{
                    $data['seo_keywords']=str_replace('[SEOstr]',$SEOstr,$class_seo['filter_keywords']);
                }

                if(empty($class_seo['filter_description'])){
                    $data['seo_desc']="LILY轴承是高质量".$SEOstr.$tit_name."的可靠供应商，可在广泛的应用中提供卓越的性能和耐用性。以优惠的价格购买我们的各种牙科轴承。";
                }else{
                    $data['seo_desc']=str_replace('[SEOstr]',$SEOstr,$class_seo['filter_description']);
                }
            }
            $data['SEOstr']=$SEOstr;
        }

        $data['crumbs']=get_crumbs($class_id);/*面包屑*/



        /*基础信息*/
        $class_fist_child=Db::table('lily_classify')->where([['status','=',1],['fid','=',$class_id]])->order('seq')->select();/*分类下是否存在子类*/

        $data['classify_content']=Db::table('lily_classify_content')->where('class_id','=',$class_id)->find();/*分类的内容信息*/
        $Esproduct = controller('index/Esproduct');

        /*判断是否是最大分类*/
        $is_max_class=Db::table('lily_classify')->where([['status','=',1],['fid','=',1],['id','=',$class_id]])->find();
        if(!empty($is_max_class)){
            $max_class=$class_id;
        }else{
            /*不是最大分类找到最大分类*/
            $max_class_arr=class_uplower($class_id);
            array_pop($max_class_arr);
            $max_class=$max_class_arr[count($max_class_arr)-1]['id'];
        }

        $data['listkey']=Db::table('lily_listkey_es4')->where([['status','=',1],['class_id','=',$class_id]])->order('seq')->select();/*左侧筛选*/

        /*不是最小分类*/
        /*在包含子类的情况下，首先要获取到所有最小分类的id，最小分类之下产品总数是否超过规定的list_page_num，不超过以左侧加多表头列表形式展示，超过则以块形式*/
        $min_class_id=array();
        $min_class_id=class_down($class_id,$min_class_id);/*获取到最小分类的id*/
        $get_transition=$get;
        unset($get_transition['page']);
        $data['get']=$get_transition;
        /*左侧不显示时*/
        if($data['class_info']['is_show_left']==0){
            if(empty($class_fist_child)){
                $right_table=Db::table('lily_right_table')->field('fileds,fileds_alias,seq,is_show')->where('class_id','=',$class_id)->order('seq')->select();
                $right_table_orders=Db::table('lily_right_table_order')->field('fileds,seq')->where('class_id','=',$class_id)->order('seq')->select();
                $table_title=[];
                $table_data=$this->no_listkey_shu_heng($right_table,$class_id,$right_table_orders);
                foreach ($right_table as $key => $value) {
                    if($value['is_show']) {
                       
                        $table_title[] = lang($value['fileds']);
                    }
                }
                $data['table_data']=$table_data;
                $data['table_title']=$table_title;
                $data['table_count']=Db::table('lily_products')->where('class_id','=',$class_id)->count();
                $is_price=Db::table('lily_products')->where([['class_id','=',$class_id],['price','<>',0]])->find();
                if(!empty($is_price)){
                   $data['is_show_price']=1;
                }else{
                    $data['is_show_price']=0;
                }
                $this->assign($data);
                $isMobile=isMobile();
                if($isMobile==1){
                    return $this->fetch('no_listkey_phone');
                }else{
                    return $this->fetch('no_listkey');
                }
            }else{
                /*不是最小分类时候，要看是否存在tag的问题*/
                $is_tag=Db::table('lily_classify')->where([['status','=',1],['fid','=',$class_id],['is_tag','=',1]])->select();
                if(empty($is_tag)){
                    $class_tag=array();
                    foreach ($class_fist_child as $key => $value) {
                        $class_tag[$key]=$value;
                        $content=Db::table('lily_classify_content')->where('class_id','=',$value['id'])->find();
                        if(empty($content)){
                            $content['block_des']='';
                        }else{
                            $content['block_des']=$content['block_des'];
                        }
                        $class_tag[$key]['block_des']=$content['block_des'];
                        $class_tag[$key]['class_url']=get_class_uplower_url($value['id']);
                    }
                    $data['class_tag']=$class_tag;
                    $this->assign($data);
                    return $this->fetch('no_list_and_tag'); /*2*/
                }else{
                    $class_tag=array();
                    $class_notag=array();
                    $i=0;
                    $j=0;
                    foreach ($class_fist_child as $key => $value) {
                        if($value['is_tag']=='1'){
                            $class_tag[$j]['first']=$value;
                            $second=Db::table('lily_classify')->where([['status','=',1],['fid','=',$value['id']]])->order('seq')->select();
                            foreach ($second as $k => $v) {
                                $content=Db::table('lily_classify_content')->where('class_id','=',$v['id'])->find();
                                if(empty($content)){
                                    $content['block_des']='';
                                }else{
                                    $content['block_des']=$content['block_des'];
                                }
                                $second[$k]['block_des']=$content['block_des'];
                                $second[$k]['class_url']=get_class_uplower_url($v['id']);
                            }
                            $class_tag[$j]['second']=$second;
                            $j++;
                        }else{
                            $class_notag[$i]['first']=$value;
                            $content=Db::table('lily_classify_content')->where('class_id','=',$value['id'])->find();
                            if(empty($content)){
                                $content['block_des']='';
                            }else{
                                $content['block_des']=$content['block_des'];
                            }
                            $class_notag[$i]['first']['class_url']=get_class_uplower_url($value['id']);
                            $class_notag[$i]['first']['block_des']=$content['block_des'];
                            $i++;
                        }
                    }
                    $data['class_tag']=$class_tag;
                    $data['class_notag']=$class_notag;
                    $this->assign($data);
                    return $this->fetch('have_tag_no_listkey'); /*3*/
                }
            }
        }else{
            $jianc=0;
            /*左侧*/
            foreach ($data['listkey'] as $key => $value) {
                if(empty($get_transition)){
                    $letget=array();
                }else{
                    $letget=array();
                    foreach ($get_transition as $k => $v) {
                        $letget[str_replace('_',' ',$k)]=$v;
                    }
                }
                $data['listkey'][$key]['data']=$Esproduct->search_data_api($letget,$min_class_id,$value['wname'],$value['is_in_m']);
                $jianc=$jianc+count($data['listkey'][$key]['data']);
            }
            if($jianc==0 && !Config::get('app.app_debug')){ // true-调试模式，测试环境;
                //header("Status: 404"); 301
                /*$this->clearfiter=1;
                dump($this->clearfiter);exit;*/
                header("Location:".$this->base_data['no_parameter_url']);
               
                exit;
                /*$get_transition=array();
                foreach ($data['listkey'] as $key => $value) {
                    if(empty($get_transition)){
                        $letget=array();
                    }else{
                        $letget=array();
                        foreach ($get_transition as $k => $v) {
                            $letget[str_replace('_',' ',$k)]=$v;
                        }
                    }
                    $data['listkey'][$key]['data']=$Esproduct->search_data_api($letget,$min_class_id,$value['wname'],$value['is_in_m']);
                    $jianc=$jianc+count($data['listkey'][$key]['data']);
                }
                $data['list_no_result_msg']="We’ve reset all filters as there are no results that match the selected filters or search terms you’ve entered.";*/
            }

            /*最小分类*/
            if(empty($class_fist_child)){
                $table_title=[];
                $table_limit=[];
                
                $right_table2=Db::table('lily_right_table')->field('fileds,fileds_alias,seq,is_show')->where('class_id','=',$class_id)->order('seq')->select();
                $right_table1=Db::table('lily_right_table1')->field('fileds,fileds_alias,seq,is_show')->where('class_id','=',$max_class)->order('seq')->select();
                if(!empty($right_table1)){
                    $right_table=[];
                    foreach ($right_table1 as $key => $value) {
                        $findfield=Db::table('lily_products_detail')->where([['key','=',$value['fileds']],['class_id','=',$class_id]])->find();
                        if(!empty($findfield)){
                            $right_table[]=$value;
                        }
                    }
                }else{
                    $right_table=$right_table2;
                }


                $right_table_orders=Db::table('lily_right_table_order')->field('fileds,seq')->where('class_id','=',$class_id)->order('seq')->select();
                if(empty($get['page'])){
                   $page=1;
                }else{
                   $page=$get['page'];
                }
                $page_start=($page-1)*Config::get('app.list_page_num');
    
                $get_transition=$get;
                unset($get_transition['page']);
                $data['get']=$get_transition;
                $table_data=$this->shu_heng($right_table,$class_id,$right_table_orders,$page_start,$get_transition);

                foreach ($right_table as $key => $value) {
                    if($value['is_show']) {
                        /*if (empty($value['fileds_alias'])) {
                            $table_title[] = $value['fileds'];
                        } else {
                            $table_title[] = $value['fileds_alias'];
                        }*/
                        $table_title[] = lang($value['fileds']);
                        $table_limit[]=$value['fileds'];
                    }
                }
                $data['table_data']=$table_data;
                $data['table_limit']=$table_limit;
                
                $data['table_title']=$table_title;
                $data['table_count']=$this->shu_heng_connt($class_id,$get_transition);
               

                $is_price=Db::table('lily_products')->where([['class_id','=',$class_id],['price','<>',0]])->find();
                if(!empty($is_price)){
                   $data['is_show_price']=1;
                }else{
                    $data['is_show_price']=0;
                }
                /*中文*/
                $data['is_show_price']=0;
                /*检测品牌*/
                $bid=Db::table('lily_products')->field('bid')->where('class_id','=',$class_id)->group('bid')->select();/*品牌id*/
                if(!empty($bid)){
                    $brand_data=array();
                    foreach ($bid as $key => $value) {
                       $brand_data[]=Db::table('lily_brand')->field('route_name,name,img')->where([['id','=',$value['bid']],['status','=',1]])->find();/*品牌id*/
                    }
                }else{
                    $brand_data=array();
                }
                //dump($data['listkey']);exit;
                $data['brand_data']=$brand_data;
                $this->assign($data);
                $isMobile=isMobile();
                if($isMobile==1){
                    return $this->fetch('min_list_phone');
                }else{
                    return $this->fetch('min_list');
                }
            }else{ 
                $table_count=0;
                $fitle_id=[];
                /*循环获取每一个最小分类，对应的筛选数据*/
                foreach ($min_class_id as $key => $value) {
                    //$num_dan=$Esproduct->search_data_count($get_transition,$value);
                    //dump($right_table);exit;
                    $num_dan=$this->shu_heng_connt($value,$get_transition);
                    if($num_dan!=0){
                        $table_count+=$num_dan;
                        $fitle_id[]=$value;
                    }
                }
                /*多表头*/
                if($table_count<=Config::get('app.list_page_num')){
                    $page_start=0;
                    $class_id_str='';
                    $table_products=array();

                    $right_table1=Db::table('lily_right_table1')->field('fileds,fileds_alias,seq,is_show')->where('class_id','=',$max_class)->order('seq')->select();
                    /*当数量小于指定数量时以多表头列表形式显示*/
                    foreach ($fitle_id as $key => $value) {

                        $right_table2=Db::table('lily_right_table')->field('fileds,fileds_alias,seq,is_show')->where('class_id','=',$value)->order('seq')->select();
                        if(!empty($right_table1)){
                            $right_table=[];
                            foreach ($right_table1 as $k1 => $v1) {
                                $findfield=Db::table('lily_products_detail')->where([['key','=',$v1['fileds']],['class_id','=',$value]])->find();
                                if(!empty($findfield)){
                                   $right_table[]=$v1;
                                }
                            }
                        }else{
                            $right_table=$right_table2;
                        }
                        //$right_table=Db::table('lily_right_table')->field('fileds,fileds_alias,seq,is_show')->where('class_id','=',$value)->order('seq')->select();

                        $right_table_orders=Db::table('lily_right_table_order')->field('fileds,seq')->where('class_id','=',$value)->order('seq')->select();
                        
                        
                        $table_data=$this->shu_heng($right_table,$value,$right_table_orders,$page_start,$get_transition);
                        
                        $table_products[$key]['class']=Db::table('lily_classify')->where([['status','=',1],['id','=',$value]])->find();

                        $table_products[$key]['class']['url']=get_class_uplower_url($value);
                        $table_products[$key]['classify_content']=Db::table('lily_classify_content')->where('class_id','=',$value)->find();/*分类的内容信息*/
                        foreach ($right_table as $k => $v) {
                            if($v['is_show']) {
                               /* if (empty($v['fileds_alias'])) {
                                    $table_products[$key]['table_title'][] = $v['fileds'];
                                } else {
                                    $table_products[$key]['table_title'][] = $v['fileds_alias'];
                                }*/
                                $table_products[$key]['table_title'][] = lang($v['fileds']);
                                $table_products[$key]['table_limit'][] = $v['fileds'];
                            }
                        }
                        $is_price=Db::table('lily_products')->where([['class_id','=',$value],['price','<>',0]])->find();
                        if(!empty($is_price)){
                           $table_products[$key]['is_show_price']=1;
                        }else{
                            $table_products[$key]['is_show_price']=0;
                        }
                        
                        $table_products[$key]['detail']=$table_data;
                        
                        $class_id_str.=$value.",";
                    }

                    $class_id_str=rtrim($class_id_str,',');
                    
                    $bid=Db::table('lily_products')->field('bid')->where('class_id','in',$class_id_str)->group('bid')->select();/*品牌id*/
                    if(!empty($bid)){
                        $brand_data=array();
                        foreach ($bid as $key => $value) {
                           $brand_data[]=Db::table('lily_brand')->field('route_name,name,img')->where([['id','=',$value['bid']],['status','=',1]])->find();/*品牌id*/
                        }
                    }else{
                        $brand_data=array();
                    }
                   
                    $data['brand_data']=$brand_data;
                    $data['table_products']=$table_products;
                    $data['table_count']=$table_count;
                    $this->assign($data);
                    $isMobile=isMobile();
                    if($isMobile==1){
                        return $this->fetch('more_title_list_phone');
                    }else{
                        return $this->fetch('more_title_list');
                    }
                    
                }else{
                    $is_tag=Db::table('lily_classify')->where([['status','=',1],['fid','=',$class_id],['is_tag','=',1]])->select();
                    /*检测手工添加品牌*/
                    $bids=Db::table('lily_classify')->field('bids')->where('id','=',$class_id)->find();
                   // echo "<pre/>";print_r($bids);exit;
                    if (!empty($bids)){
                        $bids = explode(',',$bids['bids']);
                        $brand_data=array();
                        foreach ($bids as $key => $value) {
                            $brand_data[]=Db::table('lily_brand')->field('route_name,name,img')->where([['id','=',$value],['status','=',1]])->find();/*品牌id*/
                        }
                    }else{
                        $brand_data=array();
                    }
                    $data['brand_data']=$brand_data;
                    if(empty($is_tag)){
                        if(empty($get_transition)){
                            $class_tag=array();
                            foreach ($class_fist_child as $key => $value) {
                                $class_tag[$key]=$value;
                                $content=Db::table('lily_classify_content')->where('class_id','=',$value['id'])->find();
                                if(empty($content)){
                                    $content['block_des']='';
                                }else{
                                    $content['block_des']=$content['block_des'];
                                }
                                $class_tag[$key]['block_des']=$content['block_des'];
                                $class_tag[$key]['class_url']=get_class_uplower_url($value['id']);
                            }
                            $data['class_tag']=$class_tag;
                            $class_id_str='';
                            foreach ($fitle_id as $key => $value) {
                                $class_id_str.=$value.',';
                            }
                            $class_id_str=rtrim($class_id_str,',');

                            $data['table_count']=$table_count;
                            $this->assign($data);
                            $isMobile=isMobile();
                            if($isMobile==1){
                                return $this->fetch('no_tag_have_listkey_phone');
                            }else{
                                return $this->fetch('no_tag_have_listkey');
                            }
                            
                        }else{
                            foreach ($class_fist_child as $key => $value) {
                                /*判断第一级分类是否已经是最小的分类id*/
                                $is_min=Db::table('lily_classify')->where([['status','=',1],['fid','=',$value['id']]])->find();
                                if(empty($is_min)){ /*是最小分类id*/
                                    if(in_array($value['id'],$fitle_id)){
                                        $same=Db::table('lily_classify')->where([['status','=',1],['id','=',$value['id']]])->find();
                                        $same['class_url']=get_class_uplower_url($value['id']);
                                        $class_data_return['dingwei-'.$value['id']]['max']=$same;
                                        $content=Db::table('lily_classify_content')->where('class_id','=',$value['id'])->find();
                                        if(empty($content)){
                                            $content['block_des']='';
                                        }else{
                                            $content['block_des']=$content['block_des'];
                                        }
                                        $same['block_des']=$content['block_des'];
                                        $move_ad_parameter_url=explode('?',$this->base_data['move_ad_parameter_url']);
                                        $same['class_url']=get_class_uplower_url($value['id']).'?'.$move_ad_parameter_url[1];
                                        $class_data_return['dingwei-'.$value['id']]['min'][]=$same;
                                    }
                                }else{
                                    /*不是最小分类id，先获取每一个第一级下的最小分类id*/
                                    $min_class_id=array();
                                    $min_class_id=class_down($value['id'],$min_class_id);
                                    foreach ($min_class_id as $k => $v) {
                                        if(in_array($v,$fitle_id)){
                                            if(!isset($class_data_return['dingwei-'.$value['id']])){
                                                $fu=Db::table('lily_classify')->where([['status','=',1],['id','=',$value['id']]])->find();
                                                $fu['class_url']=get_class_uplower_url($value['id']);
                                                $class_data_return['dingwei-'.$value['id']]['max']=$fu;
                                            }
                                            $zi=Db::table('lily_classify')->where([['status','=',1],['id','=',$v]])->find();
                                            $content=Db::table('lily_classify_content')->where('class_id','=',$v)->find();
                                            if(empty($content)){
                                                $content['block_des']='';
                                            }else{
                                                $content['block_des']=$content['block_des'];
                                            }
                                            $zi['block_des']=$content['block_des'];
                                            $move_ad_parameter_url=explode('?',$this->base_data['move_ad_parameter_url']);
                                            $zi['class_url']=get_class_uplower_url($v).'?'.$move_ad_parameter_url[1];
                                            $class_data_return['dingwei-'.$value['id']]['min'][]=$zi;
                                        }
                                    }
                                }
                            }
                            $class_id_str='';
                            foreach ($fitle_id as $key => $value) {
                                $class_id_str.=$value.",";
                            }
                            $class_id_str=rtrim($class_id_str,',');
                            
                            $data['class_data_return']=$class_data_return;
                            $data['table_count']=$table_count;
                            $this->assign($data);
                            $isMobile=isMobile();
                            if($isMobile==1){
                                return $this->fetch('no_tag_have_listket_have_fiter_phone');
                            }else{
                                return $this->fetch('no_tag_have_listket_have_fiter');
                            }
                        }
                    }else{
                        if(empty($get_transition)){
                            $class_tag=array();
                            $class_notag=array();
                            $i=0;
                            $j=0;
                            foreach ($class_fist_child as $key => $value) {
                                if($value['is_tag']=='1'){
                                    $class_tag[$j]['first']=$value;
                                    $second=Db::table('lily_classify')->where([['status','=',1],['fid','=',$value['id']]])->order('seq')->select();
                                    foreach ($second as $k => $v) {
                                        $content=Db::table('lily_classify_content')->where('class_id','=',$v['id'])->find();
                                        if(empty($content)){
                                            $content['block_des']='';
                                        }else{
                                            $content['block_des']=$content['block_des'];
                                        }
                                        $second[$k]['block_des']=$content['block_des'];
                                        $second[$k]['class_url']=get_class_uplower_url($v['id']);
                                    }
                                    $class_tag[$j]['second']=$second;
                                    $j++;
                                }else{
                                    $class_notag[$i]['first']=$value;
                                    $content=Db::table('lily_classify_content')->where('class_id','=',$value['id'])->find();
                                    if(empty($content)){
                                        $content['block_des']='';
                                    }else{
                                        $content['block_des']=$content['block_des'];
                                    }
                                    $class_notag[$i]['first']['class_url']=get_class_uplower_url($value['id']);
                                    $class_notag[$i]['first']['block_des']=$content['block_des'];
                                    $i++;
                                }
                            }
                            $data['class_tag']=$class_tag;
                            $data['class_notag']=$class_notag;
                            
                            $class_id_str='';
                            foreach ($fitle_id as $key => $value) {
                                $class_id_str.=$value.',';
                            }
                            $class_id_str=rtrim($class_id_str,',');
                            
                            $data['table_count']=$table_count;
                            $this->assign($data);
                            $isMobile=isMobile();
                            if($isMobile==1){
                                return $this->fetch('have_tag_have_listkey_phone');
                            }else{
                                return $this->fetch('have_tag_have_listkey');
                            }
                            
                        }else{

                            $class_id_str='';
                            foreach ($fitle_id as $key => $value) {
                                $class_id_str.=$value.",";
                            }
                            $class_id_str=rtrim($class_id_str,',');

                            $class_tag=array();
                            $class_notag=array();
                            $i=0;
                            $j=0;
                            foreach ($class_fist_child as $key => $value) {
                                $min_class_id=array();
                                $min_class_id=class_down($value['id'],$min_class_id);
                                $intersect_result=array_intersect($fitle_id,$min_class_id);/*判断是否存在交集*/
                                if(!empty($intersect_result)){
                                    if($value['is_tag']=='1'){
                                        $class_tag[$j]['first']=$value;
                                        $second=Db::table('lily_classify')->where([['status','=',1],['fid','=',$value['id']]])->order('seq')->select();
                                        foreach ($second as $k => $v) {
                                            $content=Db::table('lily_classify_content')->where('class_id','=',$v['id'])->find();
                                            if(empty($content)){
                                                $content['block_des']='';
                                            }else{
                                                $content['block_des']=$content['block_des'];
                                            }
                                            $second[$k]['block_des']=$content['block_des'];
                                            $move_ad_parameter_url=explode('?',$this->base_data['move_ad_parameter_url']);
                                            $second[$k]['class_url']=get_class_uplower_url($v['id']).'?'.$move_ad_parameter_url[1];
                                        }
                                        $class_tag[$j]['second']=$second;
                                        $j++;
                                    }else{
                                        $class_notag[$i]['first']=$value;
                                        $content=Db::table('lily_classify_content')->where('class_id','=',$value['id'])->find();
                                        if(empty($content)){
                                            $content['block_des']='';
                                        }else{
                                            $content['block_des']=$content['block_des'];
                                        }
                                        $move_ad_parameter_url=explode('?',$this->base_data['move_ad_parameter_url']);
                                        $class_notag[$i]['first']['class_url']=get_class_uplower_url($value['id']).'?'.$move_ad_parameter_url[1];
                                        $class_notag[$i]['first']['block_des']=$content['block_des'];
                                        $i++;
                                    }
                                }
                            }
                            $data['class_tag']=$class_tag;
                            $data['class_notag']=$class_notag;
                            $data['table_count']=$table_count;
                            $this->assign($data);
                            $isMobile=isMobile();
                            if($isMobile==1){
                                return $this->fetch('have_tag_have_listket_have_fiter_phone');
                            }else{
                                return $this->fetch('have_tag_have_listket_have_fiter');
                            }
                            
                        }
                    }
                }
            }

        }
                     
    }
       
        

   /*
   移除get参数中的广告参数
   并且get中 p 标签为 part_number，p是再url中显示p是为了美化。 p 目的是搜索型号
   */
   public function move_ad_and_replace_p($get){
       if(isset($get['p'])){
            $get['part_number']=$get['p'];
            unset($get['p']);
         }
         $lily_ad=Db::table('lily_ad')->field('pname')->select();
         foreach ($lily_ad as $key => $value) {
            unset($get[$value['pname']]);
         }
         return $get;
   }
   
   /*
   竖表转横表 方便列表页 表格展示 排序等等问题
   传入需要查询的key
   将key作为字段
   拼接sql 获取右侧数据
   $right_fields 右侧需要的字段
   $order_fields 排序需要的字段
   $page_start 分页开始字段
   */
   public function shu_heng($right_fields,$class_id,$order_fields,$page_start,$get_transition){
 
        $System=Db::table('lily_products_detail')->where([['class_id','in',$class_id],['key','=','System of Measurement']])->find();
        if(!empty($System)&&!in_array('System of Measurement',$right_fields)){
            $add_right_fields['fileds']='System of Measurement';
            $add_right_fields['fileds_alias']=null;
            $add_right_fields['seq']=count($right_fields);
            $add_right_fields['is_show']=0;
            $right_fields[]=$add_right_fields;
        }
        $right_table_fileds=[];
        foreach ($right_fields as $key => $value) {
            $right_table_fileds[]=$value['fileds'];
        }
        $right_table_orders_arr=[];
        if(!empty($order_fields)){
            foreach ($order_fields as $key => $value) {
                $right_table_orders_arr[]=$value['fileds']; 
            }
        }

      if(!empty($get_transition)){
        foreach ($get_transition as $key => $value) {
            if($key!='part_number'){
                if(!in_array(str_replace('_',' ',$key),$right_table_fileds)){
                   $right_table_fileds[]=str_replace('_',' ',$key);
                }
            }
        }
      }

        
      $sql="select b.part_number,a.*,b.price,b.url_product from ( SELECT pid,";
        

      foreach ($right_table_fileds as $key => $value) {
         $sql.="group_concat(case when `key` = '".$value."' then `value` else null end) as `".str_replace(' ','_',$value)."`,";
      }
      $sql=rtrim($sql,','); 
      /*排序*/
      if(empty($right_table_orders_arr)){
        $order="";
      }else{ 
         $order="order by ";
         if(in_array('System of Measurement',$right_table_fileds)){
            $order.="a.`System_of_Measurement` ASC,";/*中文站变为desc*/
         }
         foreach ($right_table_orders_arr as $key => $value) {
            //$order.="a.`".str_replace(' ','_',$value)."`+0 asc,";
            $order.="( case when LOCATE(' ',a.`".str_replace(' ','_',$value)."`)>0 and LOCATE('\"',a.`".str_replace(' ','_',$value)."`)>0 then SUBSTRING_INDEX(REPLACE(a.`".str_replace(' ','_',$value)."`,'\"',''),' ',1)+(SUBSTRING_INDEX(SUBSTRING_INDEX(REPLACE(a.`".str_replace(' ','_',$value)."`,'\"',''),' ',-1),'/',1)/SUBSTRING_INDEX(SUBSTRING_INDEX(REPLACE(a.`".str_replace(' ','_',$value)."`,'\"',''),' ',-1),'/',-1))  when LOCATE(' ',a.`".str_replace(' ','_',$value)."`)=0 AND LOCATE('/',a.`".str_replace(' ','_',$value)."`)>0  then  SUBSTRING_INDEX(SUBSTRING_INDEX(REPLACE(a.`".str_replace(' ','_',$value)."`,'\"',''),' ',-1),'/',1)/SUBSTRING_INDEX(SUBSTRING_INDEX(REPLACE(a.`".str_replace(' ','_',$value)."`,'\"',''),' ',-1),'/',-1) when LOCATE(' ',a.`".str_replace(' ','_',$value)."`)=0 AND LOCATE('/',a.`".str_replace(' ','_',$value)."`)=0 AND LOCATE(' mm',a.`".str_replace(' ','_',$value)."`)=0 AND LOCATE('\"',a.`".str_replace(' ','_',$value)."`)>0  then REPLACE(a.`".str_replace(' ','_',$value)."`,'\"','')+0 when LOCATE(' mm',a.`".str_replace(' ','_',$value)."`)>0 then REPLACE(a.`".str_replace(' ','_',$value)."`,' mm','')+0 END ) asc,";
            $order.= " case when a.`".str_replace(' ','_',$value)."` REGEXP '[0-9]'=1 then a.`".str_replace(' ','_',$value)."` end asc,";
         }
         $order=$order."replace(b.part_number,'S','') asc";
      }
      /*筛选*/
      if(empty($get_transition)){
         $where='';
      }else{
         $where=' where ';
         foreach ($get_transition as $key => $value) {
                if($key=='part_number'){
                    $where.="b.`".$key."` like '%".$value."%' and ";
                }else{
                    if(strpos($value,'~')!==false){
                        $range=explode('~',str_replace('mm','',str_replace('"','',$value)));
                        if($range[1]=='greater'){
                            $where.="a.`".$key."`>".$range[0]." and ";
                        }else{
                            $where.="a.`".$key."`>".$range[0]." and a.`".$key."`<=".$range[1]." and ";
                        }
                    }else{
                        $where.="a.`".$key."`='".$value."' and ";
                    }
                } 
            }
         $where=rtrim($where,'and ');
      }

      $sql=rtrim($sql,",")." from lily_products_detail WHERE class_id = ".$class_id." group by pid ) as a left join lily_products as b on a.pid=b.id ".$where." ".$order." limit ".$page_start.",".Config::get('app.list_page_num');
      
      //echo $sql;exit;
      return Db::Query($sql);
   }

   /*左侧筛选后的sql 以及执行结果*/
   public function left_shu_heng($class_id,$get_transition,$fields){
      $right_fields=[];
      $right_fields[]=$fields;

      $System=Db::table('lily_products_detail')->where([['class_id','in',$class_id],['key','=','System of Measurement']])->find();
      if(!empty($System)&&!in_array('System of Measurement',$right_fields)){
         $right_fields[]='System of Measurement';
      }

      if(!empty($get_transition)){
        foreach ($get_transition as $key => $value) {
            if($key!='part_number'){
                if(!in_array(str_replace('_',' ',$key),$right_fields)){
                   $right_fields[]=str_replace('_',' ',$key);
                }
            }
        }
      }

    $sql="select `".str_replace(' ','_',$fields)."` as value from ( select   a.*,b.part_number from ( SELECT pid,";
    
      foreach ($right_fields as $key => $value) {
         $sql.="max(case when `key` = '".$value."' then `value` else null end) as `".str_replace(' ','_',$value)."`,";
      } 
      $sql=rtrim($sql,',');
      /*筛选*/
      if(empty($get_transition)){
         $where='';
      }else{
         $where=' where ';
         foreach ($get_transition as $key => $value) {
                if($key=='part_number'){
                    $where.="b.`".$key."` like '%".$value."%' and ";
                }else{
                    if(strpos($value,'~')!==false){
                        $range=explode('~',str_replace('mm','',str_replace('"','',$value)));
                        if($range[1]=='greater'){
                            $where.="a.`".$key."`>".$range[0]." and ";
                        }else{
                            $where.="a.`".$key."`>".$range[0]." and a.`".$key."`<=".$range[1]." and ";
                        }
                    }else{
                        $where.="a.`".$key."`='".$value."' and ";
                    }
                }  
            }
         $where=rtrim($where,'and ');
      }

      if(in_array('System of Measurement',$right_fields)){
            $order="`System_of_Measurement` ASC,( case when LOCATE(' ',`".str_replace(' ','_',$fields)."`)>0 and LOCATE('\"',`".str_replace(' ','_',$fields)."`)>0 then SUBSTRING_INDEX(REPLACE(`".str_replace(' ','_',$fields)."`,'\"',''),' ',1)+(SUBSTRING_INDEX(SUBSTRING_INDEX(REPLACE(`".str_replace(' ','_',$fields)."`,'\"',''),' ',-1),'/',1)/SUBSTRING_INDEX(SUBSTRING_INDEX(REPLACE(`".str_replace(' ','_',$fields)."`,'\"',''),' ',-1),'/',-1))  when LOCATE(' ',`".str_replace(' ','_',$fields)."`)=0 AND LOCATE('/',`".str_replace(' ','_',$fields)."`)>0  then  SUBSTRING_INDEX(SUBSTRING_INDEX(REPLACE(`".str_replace(' ','_',$fields)."`,'\"',''),' ',-1),'/',1)/SUBSTRING_INDEX(SUBSTRING_INDEX(REPLACE(`".str_replace(' ','_',$fields)."`,'\"',''),' ',-1),'/',-1) when LOCATE(' ',`".str_replace(' ','_',$fields)."`)=0 AND LOCATE('/',`".str_replace(' ','_',$fields)."`)=0 AND LOCATE(' mm',`".str_replace(' ','_',$fields)."`)=0 AND LOCATE('\"',`".str_replace(' ','_',$fields)."`)>0  then REPLACE(`".str_replace(' ','_',$fields)."`,'\"','')+0 when LOCATE(' mm',`".str_replace(' ','_',$fields)."`)>0 then REPLACE(`".str_replace(' ','_',$fields)."`,' mm','')+0 else `".str_replace(' ','_',$fields)."`+0 END ) asc,";
            $order.= " case when `".str_replace(' ','_',$fields)."` REGEXP '[0-9]'=1 then `".str_replace(' ','_',$fields)."` end asc";/*中文站变为System_of_Measurement 为desc*/
        }else{
            $order="`".str_replace(' ','_',$fields)."`+0 asc";
        }

      $sql=rtrim($sql,",")." from lily_products_detail WHERE class_id in (".$class_id.") group by pid ) as a left join lily_products as b on a.pid=b.id ".$where." ) as c group by `".str_replace(' ','_',$fields)."` order by ".$order;
       //echo $sql;exit;
        $rdata=Db::Query($sql);
        if(count($rdata)==1&&empty($rdata[0]['value'])){
            return null;
        }else{
            return $rdata; 
        }
   }

   public function listkey_reorder_img_left($class_id,$get_transition,$fields,$list_key_id,$tab){
        $right_fields=[];
        $right_fields[]=$fields;

        if(!empty($get_transition)){
            foreach ($get_transition as $key => $value) {
                if($key!='part_number'){
                    if(!in_array(str_replace('_',' ',$key),$right_fields)){
                       $right_fields[]=str_replace('_',' ',$key);
                    }
                }
            }
        }
        
        $sql="SELECT  * FROM ".$tab." WHERE `value` IN ( select `".str_replace(' ','_',$fields)."` as value from ( select   a.*,b.part_number from ( SELECT pid,";
        foreach ($right_fields as $key => $value) {
         $sql.="max(case when `key` = '".$value."' then `value` else null end) as `".str_replace(' ','_',$value)."`,";
        } 
        $sql=rtrim($sql,',');
          /*筛选*/
        if(empty($get_transition)){
            $where='';
        }else{
             $where=' where ';
             foreach ($get_transition as $key => $value) {
                    if($key=='part_number'){
                        $where.="b.`".$key."` like '%".$value."%' and ";
                    }else{
                        if(strpos($value,'~')!==false){
                            $range=explode('~',str_replace('mm','',str_replace('"','',$value)));
                            if($range[1]=='greater'){
                                $where.="a.`".$key."`>".$range[0]." and ";
                            }else{
                                $where.="a.`".$key."`>".$range[0]." and a.`".$key."`<=".$range[1]." and ";
                            }
                        }else{
                            $where.="a.`".$key."`='".$value."' and ";
                        }
                    }  
                }
             $where=rtrim($where,'and ');
        }

        $sql=rtrim($sql,",")." from lily_products_detail WHERE class_id in ( ".$class_id.") group by pid ) as a left join lily_products as b on a.pid=b.id ".$where." ) as c group by `".str_replace(' ','_',$fields)."`) AND list_key_id=".$list_key_id." ORDER BY seq asc";

        $rdata=Db::Query($sql);
        if(count($rdata)==1&&empty($rdata[0]['value'])){
            return null;
        }else{
            return $rdata; 
        }
   }

   public function listkey_range_detail($class_id,$get_transition,$fields,$data){

        $right_fields=[];
        $right_fields[]=$fields;
        $System=Db::table('lily_products_detail')->where([['class_id','in',$class_id],['key','=','System of Measurement']])->find();
        
        if(!empty($System)&&!in_array('System of Measurement',$right_fields)&&($data['unit']=='"'||$data['unit']=='mm')){
            $right_fields[]='System of Measurement';
            if($data['unit']=='"'){$Measurement='Inch';}
            if($data['unit']=='mm'){$Measurement='Metric';}
        }

        if(!empty($get_transition)){
            foreach ($get_transition as $key => $value) {
                if($key!='part_number'){
                    if(!in_array(str_replace('_',' ',$key),$right_fields)){
                       $right_fields[]=str_replace('_',' ',$key);
                    }
                }
            }
        }

        $sql="SELECT  COUNT(`value`) AS num FROM ( select `".str_replace(' ','_',$fields)."` as value from ( select   a.*,b.part_number from ( SELECT pid,";
        
        foreach ($right_fields as $key => $value) {
         $sql.="max(case when `key` = '".$value."' then `value` else null end) as `".str_replace(' ','_',$value)."`,";
        } 
        $sql=rtrim($sql,',');
          /*筛选*/
        if(empty($get_transition)){
            
            if(in_array('System of Measurement',$right_fields)){
                $where=" where a.`System_of_Measurement`='".$Measurement."' ";
            }else{
                $where='';
            } 
        }else{
             $where=' where ';
             foreach ($get_transition as $key => $value) { 
                    if($key=='part_number'){
                        $where.="b.`".$key."` like '%".$value."%' and ";
                    }else{
                        if(strpos($value,'~')!==false){
                            $range=explode('~',str_replace('mm','',str_replace('"','',$value)));
                            if($range[1]=='greater'){
                                $where.="a.`".$key."`>".$range[0]." and ";
                            }else{
                                $where.="a.`".$key."`>".$range[0]." and a.`".$key."`<=".$range[1]." and ";
                            }
                        }else{
                            $where.="a.`".$key."`='".$value."' and ";
                        }
                    }  
                }
            if(in_array('System of Measurement',$right_fields)&&!isset($get_transition['System_of_Measurement'])){
                $where.="a.`System_of_Measurement`='".$Measurement."' and ";
            }   
             $where=rtrim($where,'and ');
        }
        $count_where='';
        if($data['times']>0){ //范围存在倍数，(min/max) * 倍数
            $data['min'] *= $data['times'];
            $data['max'] *= $data['times'];
        }

        if($data['max']=='greater'){
            $count_where.="`value`>".$data['min']." LIMIT 0,1";
        }else{
            $count_where.="`value`>".$data['min']." AND `value`<=".$data['max']." LIMIT 0,1";
        }

        $sql=rtrim($sql,",")." from lily_products_detail WHERE class_id in (".$class_id.") group by pid ) as a left join lily_products as b on a.pid=b.id ".$where." ) as c group by `".str_replace(' ','_',$fields)."`) AS m WHERE ".$count_where;
        // echo $sql;exit;
        return Db::Query($sql);
   }
   /*获取筛选后的总数*/
   public function shu_heng_connt($class_id,$get_transition){

       $right_fields=[];
       if(!empty($get_transition)){
        foreach ($get_transition as $key => $value) {
            if($key!='part_number'){
                if(!in_array(str_replace('_',' ',$key),$right_fields)){
                   $right_fields[]=str_replace('_',' ',$key);
                }
            }
        }
        
         
          $sql="select count(pid) as num from (select a.*,b.part_number from ( SELECT pid,";
         
          foreach ($right_fields as $key => $value) {
             $sql.="max(case when `key` = '".$value."' then `value` else null end) as `".str_replace(' ','_',$value)."`,";
          }
          $sql=rtrim($sql,',');
          
          /*筛选*/
          if(empty($get_transition)){
             $where='';
          }else{
             $where=' where ';
             foreach ($get_transition as $key => $value) {
                     if($key=='part_number'){
                        $where.="b.`".$key."` like '%".$value."%' and ";
                    }else{
                        if(strpos($value,'~')!==false){
                            $range=explode('~',str_replace('mm','',str_replace('"','',$value)));
                            if($range[1]=='greater'){
                                $where.="a.`".$key."`>".$range[0]." and ";
                            }else{
                                $where.="a.`".$key."`>".$range[0]." and a.`".$key."`<=".$range[1]." and ";
                            }
                        }else{
                            $where.="a.`".$key."`='".$value."' and ";
                        }
                    }  
                }
             $where=rtrim($where,'and ');
          }

          $sql=rtrim($sql,",")." from lily_products_detail WHERE class_id = ".$class_id." group by pid ) as a left join lily_products as b on a.pid=b.id ".$where.") as c" ;
      }else{
        $sql="select  count(id) as num from lily_products where class_id=".$class_id;
      }
      
      return Db::Query($sql)[0]['num'];
   }

    /*
   无左侧查询全部
   */
   public function no_listkey_shu_heng($right_fields,$class_id,$order_fields){
        $right_table_fileds=[];
        foreach ($right_fields as $key => $value) {
            $right_table_fileds[]=$value['fileds'];
        }
        $right_table_orders_arr=[];
        if(!empty($order_fields)){
            foreach ($order_fields as $key => $value) {
                $right_table_orders_arr[]=$value['fileds']; 
            }
        }
      if(!empty($get_transition)){
        foreach ($get_transition as $key => $value) {
            if($key!='part_number'){
                if(!in_array(str_replace('_',' ',$key),$right_table_fileds)){
                   $right_table_fileds[]=str_replace('_',' ',$key);
                }
            }
        }
      }

       
        $sql="select b.part_number,a.*,b.price,b.url_product from ( SELECT pid,";
        
      foreach ($right_table_fileds as $key => $value) {
         $sql.="group_concat(case when `key` = '".$value."' then `value` else null end) as `".str_replace(' ','_',$value)."`,";
      }
      $sql=rtrim($sql,',');
      /*排序*/
      if(empty($right_table_orders_arr)){
        $order="order by replace(b.part_number,'S','') ASC";
      }else{
         $order="order by ";
         if(in_array('System of Measurement',$right_table_fileds)){
            $order.="a.`System_of_Measurement` ASC,";/*中文站变为desc*/
         }
         foreach ($right_table_orders_arr as $key => $value) {
            //$order.="a.`".str_replace(' ','_',$value)."`+0 asc,";
            $order.="( case when LOCATE(' ',a.`".str_replace(' ','_',$value)."`)>0 and LOCATE('\"',a.`".str_replace(' ','_',$value)."`)>0 then SUBSTRING_INDEX(REPLACE(a.`".str_replace(' ','_',$value)."`,'\"',''),' ',1)+(SUBSTRING_INDEX(SUBSTRING_INDEX(REPLACE(a.`".str_replace(' ','_',$value)."`,'\"',''),' ',-1),'/',1)/SUBSTRING_INDEX(SUBSTRING_INDEX(REPLACE(a.`".str_replace(' ','_',$value)."`,'\"',''),' ',-1),'/',-1))  when LOCATE(' ',a.`".str_replace(' ','_',$value)."`)=0 AND LOCATE('/',a.`".str_replace(' ','_',$value)."`)>0  then  SUBSTRING_INDEX(SUBSTRING_INDEX(REPLACE(a.`".str_replace(' ','_',$value)."`,'\"',''),' ',-1),'/',1)/SUBSTRING_INDEX(SUBSTRING_INDEX(REPLACE(a.`".str_replace(' ','_',$value)."`,'\"',''),' ',-1),'/',-1) when LOCATE(' ',a.`".str_replace(' ','_',$value)."`)=0 AND LOCATE('/',a.`".str_replace(' ','_',$value)."`)=0 AND LOCATE(' mm',a.`".str_replace(' ','_',$value)."`)=0 AND LOCATE('\"',a.`".str_replace(' ','_',$value)."`)>0  then REPLACE(a.`".str_replace(' ','_',$value)."`,'\"','')+0 when LOCATE(' mm',a.`".str_replace(' ','_',$value)."`)>0 then REPLACE(a.`".str_replace(' ','_',$value)."`,' mm','')+0 END ) asc,";
            $order.= " case when a.`".str_replace(' ','_',$value)."` REGEXP '[0-9]'=1 then a.`".str_replace(' ','_',$value)."` end asc,";
         }
         $order=$order."replace(b.part_number,'S','') asc";
      }
      

      $sql=rtrim($sql,",")." from lily_products_detail WHERE class_id = ".$class_id." group by pid ) as a left join lily_products as b on a.pid=b.id  ".$order;

      return Db::Query($sql);
   }
   
   /*多个分类左侧信息*/
    public  function left_more_class($right_fields,$class_id,$get_transition,$fields){
        if(!empty($get_transition)){
            foreach ($get_transition as $key => $value) {
                if($key!='part_number'){
                if(!in_array(str_replace('_',' ',$key),$right_fields)){
                   $right_fields[]=str_replace('_',' ',$key);
                }
            }
            }
        }
        
        $sql="select `".str_replace(' ','_',$fields)."` as value from ( select  a.*,b.part_number from ( SELECT pid,";
        
        foreach ($right_fields as $key => $value) {
            $sql.="group_concat(case when `key` = '".$value."' then `value` else null end) as `".str_replace(' ','_',$value)."`,";
        } 
        $sql=rtrim($sql,',');
        /*筛选*/
        if(empty($get_transition)){
            $where='';
        }else{
            $where=' where ';
            foreach ($get_transition as $key => $value) {
                 if($key=='part_number'){
                        $where.="b.`".$key."` like '%".$value."%' and ";
                    }else{
                        if(strpos($value,'~')!==false){
                            $range=explode('~',str_replace('mm','',str_replace('"','',$value)));
                            if($range[1]=='greater'){
                                $where.="a.`".$key."`>".$range[0]." and ";
                            }else{
                                $where.="a.`".$key."`>".$range[0]." and a.`".$key."`<=".$range[1]." and ";
                            }
                        }else{
                            $where.="a.`".$key."`='".$value."' and ";
                        }
                    }  
            }
            $where=rtrim($where,'and ');
        }

        if(in_array('System of Measurement',$right_fields)){
            $order="`System_of_Measurement` ASC,( case 
            when LOCATE(' ',`".str_replace(' ','_',$fields)."`)>0 and LOCATE('\"',`".str_replace(' ','_',$fields)."`)>0 then SUBSTRING_INDEX(REPLACE(`".str_replace(' ','_',$fields)."`,'\"',''),' ',1)+(SUBSTRING_INDEX(SUBSTRING_INDEX(REPLACE(`".str_replace(' ','_',$fields)."`,'\"',''),' ',-1),'/',1)/SUBSTRING_INDEX(SUBSTRING_INDEX(REPLACE(`".str_replace(' ','_',$fields)."`,'\"',''),' ',-1),'/',-1))  
            when LOCATE(' ',`".str_replace(' ','_',$fields)."`)=0 AND LOCATE('/',`".str_replace(' ','_',$fields)."`)>0  then  SUBSTRING_INDEX(SUBSTRING_INDEX(REPLACE(`".str_replace(' ','_',$fields)."`,'\"',''),' ',-1),'/',1)/SUBSTRING_INDEX(SUBSTRING_INDEX(REPLACE(`".str_replace(' ','_',$fields)."`,'\"',''),' ',-1),'/',-1) 
            when LOCATE(' ',`".str_replace(' ','_',$fields)."`)=0 AND LOCATE('/',`".str_replace(' ','_',$fields)."`)=0 AND LOCATE(' mm',`".str_replace(' ','_',$fields)."`)=0 AND LOCATE('\"',`".str_replace(' ','_',$fields)."`)>0  then REPLACE(`".str_replace(' ','_',$fields)."`,'\"','')+0 
            when LOCATE(' mm',`".str_replace(' ','_',$fields)."`)>0 then REPLACE(`".str_replace(' ','_',$fields)."`,' mm','')+0 else `".str_replace(' ','_',$fields)."`+0 END ) asc,";
            $order.= " case when `".str_replace(' ','_',$fields)."` REGEXP '[0-9]'=1 then `".str_replace(' ','_',$fields)."`+0 end asc";/*中文站变为System_of_Measurement 为desc*/
        }else{
            $order="`".str_replace(' ','_',$fields)."`+0 asc";
        }

        $sql=rtrim($sql,",")." from lily_products_detail WHERE class_id in (".$class_id.") group by pid ) as a left join lily_products as b on a.pid=b.id ".$where." ) as c where (`".str_replace(' ','_',$fields)."` is not null or `".str_replace(' ','_',$fields)."` !='') group by `".str_replace(' ','_',$fields)."` order by ".$order;
        //echo $sql;exit;
        return Db::Query($sql);
    }
    
    /*产品详情页面*/
    public function detail(Request $request){
        $part_number_url = request()->param()['part_number'];
        $products=Db::table('lily_products')->where('url_product','=',$part_number_url)->find();
        if(empty($products)){
            if (strpos($part_number_url,'_')) {
                $part_number_url_ex = explode('_',$part_number_url)[0];
                $is_exist = Db::table('lily_products')->where('url_product','=',$part_number_url_ex)->find();
                if (!empty($is_exist)) {
                    http_response_code(301);
                    header("Location:/products/".$part_number_url_ex."/");
                    exit;
                }
            }
        }
    
        if(empty($products)){
            header("Status: 404");
            return $this->fetch('404/404');
        }
        $pid = $products['id'];
        $class_id = $products['class_id'];

        $detail=Db::table('lily_products_detail')->where([['pid','=', $pid], ['is_show', '=', 1]])->order(['seq','id'])->select();
        $class=Db::table('lily_classify')->where([['status','=',1],['id','=',$class_id]])->find();
        $class_seo=Db::table('lily_classify_seo')->where([['status','=',1],['class_id','=',$class_id]])->find();
        $equivalent=Db::table('lily_equivalent')->where('pid','=', $pid)->find();
        $detail_des=Db::table('lily_classify_content')->field('detail_des')->where('class_id','=', $class_id)->find();
        if(!empty($detail_des)){
            $sql = "SELECT `key`, `value` FROM lily_products_detail WHERE pid=$pid AND is_show=1 ORDER BY LENGTH(`key`) DESC";
            $pd = DB::query($sql);
            $h1=$products['part_number'];
            $content=str_replace('[H1]', $h1, $detail_des['detail_des']);
            foreach ($pd as $vv) {
                $ky = str_replace(' ', '_', $vv['key']);
                $va = $vv['value'];
                if(strpos($content, $ky)!==false && !empty($va)){
                    $content=str_replace($ky, lang($va), $content);
                }
            }
            $data['content']=$content;
        }else{
            $data['content']='';
        }

        $zhu['Part Number']=$products['part_number'];
        if(!empty($equivalent)){
            $zhu['Equivalent to Manufacturer']='<a href="'.$equivalent['url'].'">' . $equivalent['name'] .'</a>';
        }else{
            if(!empty($products['bid'])){
                $lily_brand_Equivalent=Db::table('lily_brand')->field('name,route_name')->where('id',$products['bid'])->find();
                if(!empty($lily_brand_Equivalent)){
                   $zhu['Equivalent to Manufacturer']='<a href="/product/brand/'.$lily_brand_Equivalent['route_name'].'/">' . $lily_brand_Equivalent['name'] .'</a>';
                }
            }
        }
        $standard_reference=Db::table('lily_products_detail')->field('value')->where([['pid','=', $pid], ['is_show', '=', 1],['key','=','Standard Reference']])->find();
        if(!empty($standard_reference)){
           $zhu['Standard Reference']=$standard_reference['value'];
        }
        $Measurement=Db::table('lily_products_detail')->field('value')->where([['pid','=', $pid], ['is_show', '=', 1],['key','=','System of Measurement']])->find();
        if(!empty($Measurement)){
            $zhu['System of Measurement']=$Measurement['value'];
        }
        foreach($detail as $k=>$v){
            $key = $v['key'];
            $value = $v['value']; 
            $zhu[$key] = $value;
        }
        /*es 推荐 数据 */
        $last_product_sql="select * from lily_products order by id desc limit 0,5";
        $last_product=Db::query($last_product_sql);
        $last_product_all=array();
        foreach ($last_product as $key => $value) {
           $last_product_all[]=$value['url_product'];
        }
        if(in_array($products['url_product'],$last_product_all)){
           $recommend_result=$last_product;
        }else{
           $zhui_five_sql="select * from lily_products where id > ".$pid." limit 0,5";
           $recommend_result=Db::query($zhui_five_sql);
        }

        /*型号兑换*/
        $sql = "SELECT b.name brand_name, a.cross_number FROM lily_cross a INNER JOIN lily_cross_brand b on b.id=a.cb_id WHERE FIND_IN_SET($pid, a.pid)>0";
        $Chat_relation = Db::Query($sql);
        if(!empty($Chat_relation)){
            $data['Chat_data']['LILY'] = 'L'. $products['part_number'];
            foreach($Chat_relation as $k=>$v){
                $key = $v['brand_name'];
                $val = $v['cross_number'];
                $data['Chat_data'][$key] = $val;
            }
           $data['Chat_relation'] = '养贞轴承型号系列'.$products['part_number'].'是这些常见轴承零件号的潜在替代品';
        }
        // More Technical Information
        $technical=Db::table('lily_product_technical')->where('pid','=', $pid)->find();
        if(!empty($technical)){
            $name = $technical['name'];
            $data['add_content'][] = "<a href='/".get_class_uplower_url($technical['class_id'])."'>" . $name ."</a>";
        }
        /*dump($technical);exit;*/
        if(!empty($products['add_content'])){
            $data['add_content'][] = $products['add_content'];
        }
        
        $data['zhu']=$zhu;
        $data['classdesc'] = $class;
        $data['products'] = $products;
        $data['recommend_result']=$recommend_result;

        // 面包屑
        $data['crumbs']=get_crumbs($class_id);


        // 型号兑换
        //查看是否对指定型号的seo做过特殊设计

        $data['base_data']=$this->base_data;
        
        /*seo*/
        /*$title_class=class_uplower($class_id);
        $title_class_second=$title_class[count($title_class)-2]['cname'];*/
        /*$description='Lily '.$products['part_number']." ".$title_class_second.", ";
        foreach ($detail as $key => $value) {
            $description.=$value['key']." ".$value['value'].", ";
        }
        $description=trim($description,', ');*/
        if(array_search('Fastening and Joining',array_column($data['crumbs'],'cname'))){
            $description="探索满足您所有工业、汽车和机械需求的各种高品质螺钉。使用我们的".strtoupper($products['part_number'])."螺钉体验增强的耐用性、高精度和卓越的效率。";
        }else if(array_search('Gears',array_column($data['crumbs'],'cname'))){
            $description="探索满足您所有工业、汽车和机械需求的各种高品质齿轮。通过我们的".strtoupper($products['part_number'])."齿轮体验增强的耐用性、高精度和卓越的效率。请访问我们以获取您所有的齿轮解决方案";
        }else{
            $description="探索满足您所有工业、汽车和机械需求的各种高品质轴承。通过我们的".strtoupper($products['part_number'])."轴承体验增强的耐用性、高精度和卓越的效率。请访问我们，了解您所有的轴承解决方案。";
        }
        if(!empty($class['alias_name'])){
            $title_class_second=$class['alias_name'];
        }else{
            $title_class_second=$class['cname'];
        }
        //dump($class);exit;
        $lily_brand=Db::table('lily_equivalent')->field('name')->where('pid',$products['id'])->find();
        if(!empty($lily_brand)){
            //$lily_brand=Db::table('lily_brand')->field('name')->where('id',$products['bid'])->find();
            $title=strtoupper($products['part_number'])." | ".$title_class_second." - ".$lily_brand['name']." | Lily Bearing";
            $keywords=strtoupper($products['part_number'])." | ".$title_class_second." - ".$lily_brand['name'];
        }else{
            if(!empty($products['bid'])){
                $lily_brand_Equivalent=Db::table('lily_brand')->field('name,route_name')->where('id',$products['bid'])->find();
                if(!empty($lily_brand_Equivalent)){
                    $title=strtoupper($products['part_number'])." | ".$title_class_second." - ".$lily_brand_Equivalent['name']." | Lily Bearing";
                    $keywords=strtoupper($products['part_number'])." | ".$title_class_second." - ".$lily_brand_Equivalent['name'];
                }
            }else{
                $standard_reference=Db::table('lily_products_detail')->where([['pid','=', $pid], ['is_show', '=', 1],['key','=','Standard Reference']])->find();
                if(empty($standard_reference)){
                    $title=strtoupper($products['part_number'])." | ".$title_class_second." | 养贞轴承";
                    $keywords=strtoupper($products['part_number'])." | ".$title_class_second;
                }else{
                    $title=strtoupper($products['part_number'])." | ".$title_class_second." - ".$standard_reference['value']." | 养贞轴承";
                    $keywords=strtoupper($products['part_number'])." | ".$title_class_second." - ".$standard_reference['value'];
                }
            }
        }
        $data['seo_title']=$title;
        $data['seo_keywords']=$keywords;
        $data['seo_desc']=$description;


        /*右侧pdf截图*/
        if(!empty($products['dimg'])){ $data['dimg']=Config::get('app.images_host').$products['dimg']; }else{ $data['dimg']=''; }
        /*左侧实物图*/
        if(!empty($products['img'])){ $data['img']=Config::get('app.images_host').$products['img']; }else{ $data['img']=''; }
        /*右侧pdf*/
        if(!empty($products['pdf'])){ $data['pdf']=Config::get('app.pdf_host').$products['pdf']; }else{ $data['pdf']=''; }
        /*右侧3d*/
        if(!empty($products['stp'])){
           $stp=json_decode($products['stp'],true);
           foreach ($stp as $key => $value) {
              $data['stp'][$key]=Config::get('app.images_host').$stp[$key];
           } 
        }else{ $data['stp']=''; }

        $data['other'] = empty($products['other']) ? '':json_decode($products['other'], true);
        
        /*canonical*/
        //change_lower_symbol($products['part_number'])
        $is_canonical=explode('_',$part_number_url);
        if(count($is_canonical)>1){
            $data['base_data']['canonical_url']=http_type().config('app.web_host_name')."/products/".$is_canonical[0]."/";
        }
        //$data['base_data']['canonical_url']=http_type().config('app.web_host_name')."/products/".change_lower_symbol($products['part_number'])."/";


        // dump($zhu);die;
        $this->assign($data);
        $isMobile=isMobile();
        if($isMobile!=1){
            return $this->fetch();
         }else{
            return $this->fetch('detail01_phone');
        }
    }


    public function list_seo(){
        $data['seo_title']=str_replace('[SEOstr]',$SEOstr,$classdesc['sel_title']);
        $data['seo_keywords']=str_replace('[SEOstr]',$SEOstr,$classdesc['sel_keyword']);
        $data['seo_desc']=str_replace('[SEOstr]',$SEOstr,$classdesc['sel_description']);
    }

    public function detail_error_404(){
        $default_lang=config('app.default_lang');
        
        $data['base_data']=$this->base_data;
        if($default_lang=='en-us'){
            $data['seo_title']="404 | Lily Bearing";
            $data['seo_keywords']="404 | Lily Bearing";
        }
        if($default_lang=='zh-cn'){
            $data['seo_title']="404 | 养贞轴承";
            $data['seo_keywords']="404 | 养贞轴承";
        }
        $data['seo_desc']="404";/*为了检测该页面是否可以访问通 不可更改*/
        return $data;
    }
    
}    